package com.ruoyi.service.project.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.service.project.entity.ProjectLogEntity;
import com.ruoyi.service.project.mapper.ProjectLogMapper;
import com.ruoyi.service.project.model.ProjectLogModel;
import com.ruoyi.service.project.service.ProjectLogService;
import com.ruoyi.service.user.model.UserInfoModel;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 项目变更记录 服务实现类
 * </p>
 *
 * @author Zane
 * @since 2025-10-12
 */
@Service
public class ProjectLogServiceImpl extends ServiceImpl<ProjectLogMapper, ProjectLogEntity>
    implements ProjectLogService {

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void saveLog(ProjectLogModel logModel, UserInfoModel userInfo) {
    if (Objects.isNull(logModel)) {
      return;
    }
    List<ProjectLogEntity> logEntities = new ArrayList<>();
    logModel.getProjectLogListNoneNull().forEach(log -> {
      logEntities.add(new ProjectLogEntity()
          .setProjectId(logModel.getProjectId())
          .setChangeData(JSONUtil.toJsonStr(log))
          .setCreateBy(userInfo.getUserId())
          .setCreateName(userInfo.getName())
          .setCreateTime(LocalDateTime.now()));
    });
    if (CollUtil.isNotEmpty(logEntities)) {
      this.saveBatch(logEntities);
    }
  }

  @Override
  public List<ProjectLogEntity> listByProjectId(String projectId) {
    return list(baseQuery().eq(ProjectLogEntity::getProjectId, projectId)
        .orderByDesc(ProjectLogEntity::getId));
  }

  private LambdaQueryWrapper<ProjectLogEntity> baseQuery() {
    return new LambdaQueryWrapper<>();
  }
}
